from tkinter import *
from config import *
from matplotlib.pylab import mpl
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

import matplotlib
import matplotlib.pyplot as plt
import tkinter.font as tf
import tkinter.messagebox
import listPage
import requests
import json


class InfoPage(object):

    data = None

    def __init__(self, master=None):
        self.root = master
        self.trends = []
        self.info = self.get_game_info()
        self.create_matplotlib()
        self.createPage()

    def createPage(self):
        self.root.update()
        width = self.root.winfo_width()
        height = self.root.winfo_height()
        self.frame = Frame(self.root, width=width, height=height)
        self.frame.pack()
        # 上半篇
        frameTop = Frame(self.frame,bd=2, bg='blue', width=width, height=height*0.2)
        frameTop.pack()

        # 返回列表按钮
        backBut = Button(frameTop, text='返回', command=self.backBut)
        backBut.pack(side=LEFT)

        # 中间部分
        frameMiddle =Frame(self.frame, width=width, height=height*0.4)
        frameMiddle.pack()

        # 第一行
        frameFrt = Frame(frameMiddle, width=width, height=height*0.1)
        frameFrt.pack()
        # 名称
        labelName1 = Label(frameFrt, text='名称:', font=('微软雅黑', 15, 'bold'))
        labelName1.pack(side=LEFT)
        labelName2 = Label(frameFrt, text=self.info.get('game_name'), font=('微软雅黑', 10))
        labelName2.pack(side=LEFT)
        # 评分
        labelScore1 = Label(frameFrt, text='评分:', font=('微软雅黑', 15, 'bold'))
        labelScore1.pack(side=LEFT)
        labelScore = Label(frameFrt, text=self.info.get('game_score'), font=('微软雅黑', 10))
        labelScore.pack(side=LEFT)

        # 第二行
        frameSec = Frame(frameMiddle, width=width, height=height*0.1)
        frameSec.pack()
        # 类型
        labelType1 = Label(frameSec, text='类型:', font=('微软雅黑', 15, 'bold'))
        labelType1.pack(side=LEFT)
        labelType = Label(frameSec, text=self.info.get('game_tab'), font=('微软雅黑', 10))
        labelType.pack(side=LEFT)
        # 日期
        labelDate1 = Label(frameSec, text='日期:', font=('微软雅黑', 15, 'bold'))
        labelDate1.pack(side=LEFT)
        labelDate = Label(frameSec, text=self.info.get('game_date'), font=('微软雅黑', 10))
        labelDate.pack(side=LEFT)


        # 第三行
        frameThi = Frame(frameMiddle, width=width, height=height*0.2)
        frameThi.pack()
        # 简介
        briefIntroductionText = Text(frameThi, width=width)
        ft = tf.Font(family='微软雅黑',size=10)
        briefIntroductionText.tag_add('tag', INSERT)
        briefIntroductionText.tag_config('tag', font=ft)
        briefIntroductionText.insert(INSERT,
                                     "  "+self.info.get('game_brief_introduction'),
                                     'tag')
        briefIntroductionText["state"] = DISABLED
        briefIntroductionText.pack()

        # 下半篇
        frameBelow = Frame(self.frame, width=width, height=height*0.4)
        frameBelow.pack()
        canvas = FigureCanvasTkAgg(self.figure,frameBelow)
        canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
        # labelBelow = Label(frameBelow, text='这里是折线图', font=('微软雅黑', 15, 'bold'))
        # labelBelow.pack()

    def backBut(self):
        self.frame.destroy()
        # plt.cla()
        plt.clf()
        listPage.ListPage(self.root)

    # 获取详情数据
    def get_game_info(self):
        url = Config.beas_url + '/get_game_info'
        headers = {'user-agent': Config.get_ua(Config)}
        param = {'game_id': self.data}
        try:
            ret = requests.get(url, params=param, headers=headers)
            retJson = json.loads(ret.text)
            list = retJson.get('data')
            self.trends = retJson.get('trends')
            if len(list) > 0:
                return list[0]
            else:
                return None
        except Exception as e:
            print(e)
            tkinter.messagebox.showerror('错误', '网络异常')
            return None

    # 绘制折线图
    def create_matplotlib(self):
        # 中文支持
        mpl.rcParams['font.sans-serif'] = ['SimHei']
        #  用来正常显示中文标签
        # 用来正常显示负号
        mpl.rcParams['axes.unicode_minus'] = False
        # 创建绘图对象f figsize的单位是英寸 像素 = 英寸*分辨率
        self.figure = plt.figure(num=self.data, figsize=(15, 6), dpi=80, facecolor="gold", edgecolor='green', frameon=True)
        # 创建一副子图(三个参数，依次是：行，列，当前索引)
        fig1 = plt.subplot(1, 1, 1)
        x = []
        y_positive_count = []
        y_negative_count = []
        for i in self.trends:
            x.append(i.get('date'))
            y_positive_count.append(i.get('positive_count'))
            y_negative_count.append(i.get('negative_count'))

        line_positive_count = fig1.plot(x, y_positive_count, color='red', linewidth=2, label='好评数', linestyle='--')
        line_negative_count = fig1.plot(x, y_negative_count, color='blue', label='差评数')
        plt.setp(line_negative_count, linewidth=1, linestyle='-', alpha=0.7)
        plt.legend()
        fig1.set_title("近一个月好评与差评趋势图", loc='center', pad=20, fontsize='xx-large')
        fig1.set_xlabel('时间')
        fig1.set_ylabel("数量")
        plt.yticks([])
